/*
 * @Author: Hunter
 * @Date: 2022-03-10 22:59:59
 * @LastEditTime: 2022-12-05 17:04:31
 * @LastEditors: Hunter
 * @Description: 
 * @FilePath: \book_mark_private\src\utils\file.ts
 * 可以输入预定的版权声明、个性签名、空行等
 */
import type { UploadFile } from "element-plus/es/components/upload/src/upload.type";
import { defer } from "utils-lib-js";
export type readFileType = 'readAsArrayBuffer' | 'readAsBinaryString' | 'readAsDataURL' | 'readAsText'
export declare interface IFileSystem {
    readFile: (file: UploadFile, type?: readFileType, encoding?: string) => Promise<ProgressEvent<FileReader>>
    downloadFile: (url: string, name?: string) => void
    stringToBlobURL: (fileString: string) => string
}
export class FileSystem implements IFileSystem {
    /**
     * @name: 
     * @description: 读取前端上传的文件
     * @param {UploadFile} file 文件
     * @param {readFileType} type 文件类型
     * @param {string} encoding 解码方式
     * @return {Promise<ProgressEvent<FileReader>>}
     */
    readFile(file: UploadFile, type: readFileType = 'readAsText', encoding: string = 'utf-8') {
        const { promise, resolve, reject } = defer()
        const reader: FileReader = new FileReader();
        reader[type](file.raw, encoding)
        reader.onload = resolve
        reader.onerror = reject
        return <Promise<any>>promise
    }
    /**
     * @name: 
     * @description: 下载文件
     * @param {string} url 资源目录/网址
     * @param {string} name 下载文件名
     * @return {*}
     */
    downloadFile(url: string, name: string = 'file.txt') {
        const link = document.createElement('a')
        link.href = url
        link.download = name
        const _evt = new MouseEvent('click')
        link.dispatchEvent(_evt)
    }
    /**
     * @name: 
     * @description: 字符串转本地文件
     * @param {string} fileString 文件内容
     * @return {*}
     */
    stringToBlobURL(fileString: string) {
        return URL.createObjectURL(new Blob([fileString], { type: "application/octet-stream" }))
    }
}
export const fileSystem = new FileSystem()